import {Button, Col, message, Modal, Row, Space, Typography, Upload, UploadProps} from "antd";
import {
  DownloadApi, DownloadAttachApi, GetAttachList,
  NoDataAPI,
  SchoolPass,
  SchoolReject, SubmitAttachApi,
  UploadApi,
  UploadAttachApi
} from "@/services/School/SchoolApi";
import {DownloadOutlined, UploadOutlined} from "@ant-design/icons";
import {history} from "umi";
import { ExclamationCircleOutlined } from '@ant-design/icons';
import {ServerMessages} from "@/services/ServerMessages";
import {ShowError} from "@/utils/format";
import type {RcFile, UploadFile} from 'antd/es/upload/interface';
import {nanoid} from "@ant-design/pro-components";
import moment from "moment";
import React, {useEffect, useState} from "react";
import {DownloadByNameApi} from "@/services/Province/ProvinceApi";

const { confirm } = Modal;

// // 上传之前的判断
// const beforeUpload = (file: RcFile) => {
//   console.log("@@file", file)
//   const isJpgOrPng = file.type === 'application/pdf'
//   if (!isJpgOrPng) {
//     ShowError('仅限pdf文件！')
//   }
//   const isLt2M = file.size / 1024 / 1024 < 20;
//   if (!isLt2M) {
//     ShowError('文件大小不能超过20M！')
//   }
//   return isJpgOrPng && isLt2M;
// };
//
// // 上传组件的参数
// const upprops: UploadProps = {
//   name: 'file', // 后端通过 name 接收该文件
//   action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76', // 后端地址 Address
//   headers: { // 请求头，包含认证信息等
//     authorization: 'authorization-text',
//   },
//   onChange(info) { // Status Change 上传文件、上传中、上传结束的回调
//     if (info.file.status !== 'uploading') {
//       console.log(info.file, info.fileList);
//     }
//     if (info.file.status === 'done') {
//       message.success(`${info.file.name} file uploaded successfully`);
//     } else if (info.file.status === 'error') {
//       message.error(`${info.file.name} file upload failed.`);
//     }
//   },
//   // defaultFileList: 已上传的文件列表
//   beforeUpload: beforeUpload
// };


export default (props) => {


  // // ************************ 新版附件 start ************************
  // // ************************ 附件功能开关 start ************************
  // 在 closeList 中搜索当前表格(download)是否存在其中，若是则设置 closeFlag 为 true，表示不显示附件上传插件
  const closeList = {
    "4_3_2": "国际合作论文数量",
    "3_1_1": "学科师德师风建设情况",
    "2_2_7": "本科生、硕士生、博士生（含留学生）发表的代表性论文清单",
    "3_2_2_3": "高层次人才存量清单",
    "5_2_1_2": "省部级产教融合平台建设数",
    "2_2_2_2": "一流本科专业建设情况",
    "3_3_3": "教师参加本领域重要学术会议并作报告人员清单",
    "3_3_4": "教师担任国际比赛评委、裁判人员清单",
    "2_2_3_0": "人才培养平台/基地建设存量情况",
    "5_4_1": "科教协同育人情况写实",
    "1_1_1": "学科建设进展情况写实",
    "2_2_2_1": "出版教材质量",
    "2_3_2": "学科领域突出贡献者情况",
    "4_1_1_0": "教师获国内外重要奖项数存量",
    "4_1_3_0": "教师在国内外期刊发表的代表性论文存量及清单",
    "2_2_1_0": "教学成果奖存量情况",
    "2_2_3_2": "省部级人才培养平台/基地建设情况",
    "4_2_2_0": "主持科研项目存量及清单",
    "2_2_5": "给本科生上课的正教授人数",
    "2_3_1": "年度授予学士、硕士、博士学位情况",
    "2_1_1": "思想政治政教育特色与成效",
    "1_1_3": "学科影响力情况",
    "4_2_1_0": "科研创新平台建设存量及清单",
    "2_2_4": "硕士导师和博士导师情况",
    "3_2_2_0": "高层次团队存量清单",
    "5_3": "服务社会",
    "4_2_1_3": "省部级平台清单",
  } // 关闭列表
  let closeFlag = false // 当前附件是否开启
  for (const closeListKey in closeList) {
    if (props.download === closeListKey) {
      closeFlag = true
      break
    }
  }
  console.log("附件是否关闭：", closeFlag)
  // // ************************ 附件功能开关 end ************************

  // ************************ 附件说明 start ************************
  // 在 attachInfo 中搜索 download 对应的说明，若 download 对应项不存在则不显示说明！
  const attachInfo = {
    "4_2_2_2": "国家重大重点项目要有立项通知;国家基金要提供基金委每年发给学校的红头文件;其他国家级项目都需有立项或其他证明文件;",
    "2_2_2_3": "需要",
    "2_2_1_2": "需要",
    "3_2_2_2": "全职人员，以学科为单位，清单盖人事处章。",
    "3_2_2_1": "需要",
    "4_2_3": "统计金额超过100万的，盖财务章即可",
    "2_2_1_3": "一等奖及以上需要",
    "4_2_4": "中国科技期刊卓越行动计划涵盖的期刊",
    "4_3_1": "需要",
    "2_2_3_1": "需要",
    "3_3_1": "副主编及以上提供",
    "3_3_2": "正职提供",
    "3_2_4": "人事处盖章名单",
    "4_2_2_3": "需要",
    "5_2_2_2": "需要",
    "4_2_3_1": "以学科为单位，由财务统出证明",
    "4_1_4": "需要",
    "2_2_6": "国家级一等奖及以上提供",
    "4_1_1_2": "一等奖及以上需要",
    "2_4_1": "清单学校盖章",
    "3_2_5": "清单学校盖章",
    "4_2_2_1": "国家重大重点项目要有立项通知;国家基金要提供基金委每年发给学校的红头文件;其他国家级项目都要有立项文件",
    "1_1_2": "需要",
    "5_2_1_1": "需要",
    "5_1_1": "财务盖章证明材料",
    "2_2_1_1": "需要",
    "2_2_2_4": "清单学校盖章",
    "4_1_2": "清单学校盖章",
    "5_2_2_1": "需要",
    "4_1_1_1": "需要",
    "4_1_3_1": "论文首页（分研究型高校、应用型高校提供）",
    "3_2_3": "清单学校盖章",
    "3_2_1": "清单学校盖章",
    "4_1_3_2": "论文首页（分研究型高校、应用型高校提供）",
    "2_4_2": "清单学校盖章",
    "4_2_1_1": "需要",
    "1_1_4": "财务盖章证明材料",
    "4_1_3_3": "论文首页（分研究型高校、应用型高校提供）",
    "3_2_2_4": "需要",
  }
  const attachInfoStr = attachInfo[props.download] ? attachInfo[props.download] : ""
  // ************************ 附件说明 end ************************
  // // ************************ 新版附件 end ************************



  // // ************************ 附件功能开关 start ************************
  // const closeList = ['2_2_1_0','4_1_3_0','4_2_2_0','2_2_3_0','4_1_1_0','3_2_2_3','3_2_2_0','4_2_1_0']
  // let closeFlag = false
  // for (const closeListKey in closeList) {
  //   if (props.download === closeList[closeListKey]) {
  //     closeFlag = true
  //     break
  //   }
  // }
  // console.log("附件是否关闭：", closeFlag)
  // // ************************ 附件功能开关 end ************************

  // ************************ 上传附件配置 start ************************
  const [fileList, setFileList] = useState([]);
  const upprops = UploadAttachApi('/api/upload-attachment', (info) => {
    console.log("上传附件返回值：", info)
    if (info.file.response.status === 0) {
      setFileList([...fileList, info.file.response.data[0].path]);
    } else {
      ShowError(info.file.response.message)
    }
  }, (info) => {
    console.log("删除的info", info)
    let tempList = []
    for (const fileListKey in fileList) {
      if (fileList[fileListKey] !== info.response.data[0].path) {
        tempList.push(fileList[fileListKey])
      }
    }
    setFileList(tempList)
    console.log("删除后的上传队列：", tempList)
  })
  // ************************ 上传附件配置 end ************************

  const status_is_check = history.location.query.flag
  const is_seen = history.location.query.is_seen
  const [uploadKey, setUploadKey] = useState(Math.random())

  // ************************ 附件列表 start ************************
  const [attachList, setAttachList] = useState([]);
  const [reload, setReload] = useState(true)
  if (!closeFlag) {
    useEffect(() => {
      // 如果是查看或者审核界面，则请求附件列表
      // 如果附件列表有返回值,则更新 attachList
      // attachList 会联动下载附件按钮展示，在填报、查看、者审核界面显示！
      GetAttachList('/api/attach-query-download', props.download, history.location.query.name).then(res => {
        console.log("获取附件列表返回值：", res)
        if (res.status === 0) {
          const {filenameList} = res
          setAttachList(filenameList)
        }
      })
    }, [reload])
  }
  // ************************ 附件列表 end ************************


  // 审核
  const handleCheck = () => {
    SchoolPass(history.location.query.id).then(response => {
      console.log(response)
      if (response.status === 0) {
        message.success(response.message)
        history.goBack()
      } else {
        ShowError(response.message)
      }
    })
    // history.goBack()
  }

  const showConfirm = () => {
    confirm({
      title: '您确认驳回吗?',
      icon: <ExclamationCircleOutlined />,
      content: '驳回后，学科用户可重新填报。',
      onOk() {
        SchoolReject(history.location.query.id).then(response => {
          if (response.status === 0) {
            message.success(response.message)
            history.goBack()
          } else {
            ShowError(response.message)
          }
        }, () => {
          ShowError(ServerMessages.error_message)
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };


  const handleBack = () => {
    showConfirm()
    // SchoolReject(history.location.query.fill_id).then(response => {
    //   if (response.status === 0) {
    //
    //   } else {
    //     ShowError(response.message)
    //   }
    // })
  }

  // 提交附件的等待按钮
  const [attachLoading, setAttachLoading] = useState(false)

  if (status_is_check === "check") {
    if (is_seen === '1') {
      return (
        <Row>
          <Col offset={8}>
            <Space>
              {attachList.map((item, idx) => {
                return <Button onClick={() => {
                  DownloadAttachApi(props.download, history.location.query.name, item)
                }
                } key={item}>下载附件{idx+1}</Button>
              })}
              <Button onClick={() => { history.goBack() }}>返回</Button>
              <Button disabled>已审核</Button>
            </Space>
          </Col>
        </Row>
      )
    }
    return (
      <Row>
        <Col offset={8}>
          <Space>
            {attachList.map((item, idx) => {
              return <Button onClick={() => {
                DownloadAttachApi(props.download, history.location.query.name, item)
              }
              } key={item}>下载附件{idx+1}</Button>
            })}
            <Button onClick={() => { history.goBack() }}>返回</Button>
            <Button onClick={handleCheck} type="primary">通过</Button>
            <Button danger onClick={handleBack}>驳回</Button>
          </Space>
        </Col>
      </Row>
    )
  } else if (status_is_check === "display") {
    return (<Row>
      <Col offset={8}>
        <Space>
          {attachList.map((item, idx) => {
            return <Button onClick={() => {
              DownloadAttachApi(props.download, history.location.query.name, item)
            }
            } key={item}>下载附件{idx+1}</Button>
          })}
          <Button onClick={() => { history.goBack() }}>返回</Button>
          <Button disabled>已提交</Button>
        </Space>
      </Col>
    </Row>)
  } else {
    return (
      <>
        <Row justify="space-between">
          <Col span={8}>
            <Space>
              <Button onClick={() => {
                console.log("@开始下载")
                DownloadApi(props.download)
              }} icon={<DownloadOutlined/>}>下载模板</Button>
              <Upload {...props.upload}>
                <Button type="primary" icon={<UploadOutlined/>}>上传模板</Button>
              </Upload>
            </Space>
            <br/>
            <br/>
          </Col>
          <Col span={8}>
            <Row justify="end">
              <Col>
                <Space>
                  <Button onClick={() => { history.goBack() }}>返回</Button>
                  <Button onClick={() => {
                    props.save()
                  }}>保存</Button>
                  <Button onClick={() => {

                    confirm({
                      title: '确定提交当前表单？',
                      icon: <ExclamationCircleOutlined />,
                      onOk() {
                        console.log('OK');
                        NoDataAPI(props.download).then(res => {
                          if (res.status === 0) {
                            message.success(res.message)
                            history.goBack()
                          } else {
                            ShowError("提交失败，请稍后重试.")
                          }
                        }, () => {
                          ShowError(ServerMessages.error_message)
                        })
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    })
                  }}>无相关数据</Button>
                  {props.doms}
                </Space>
              </Col>
            </Row>
          </Col>
        </Row>
        {!closeFlag && (
          <>
            <div style={{height: 20}}></div>
            <Typography.Title level={2}>附件说明：{attachInfoStr}</Typography.Title>
            <Space>
              <div key={uploadKey}>
                <Upload {...upprops}>
                  <Button type="default" icon={<UploadOutlined/>}>上传附件</Button>
                </Upload>
              </div>
              <Button loading={attachLoading} type="primary" onClick={() => {
                setAttachLoading(true)
                SubmitAttachApi('/api/upload-attachment-sub', props.download, fileList).then(res => {
                  if (res.status === 0) {
                    Modal.success({
                      title: <span>附件上传成功！您可以点击下方的按钮进行查看。</span>,
                    })
                    // 刷新下载列表
                    setReload(!reload)
                    // ant upload 清空已上传列表
                    setUploadKey(Math.random())
                    setFileList([])
                  } else {
                    ShowError(res.message)
                  }
                  setAttachLoading(false)
                }, () => {
                  ShowError(ServerMessages.error_message)
                  setAttachLoading(false)
                })
              }}>提交附件</Button>
              <Typography.Text type="danger">相关证明材料请在提交时上传，仅限pdf格式。（最多上传10个文件，总大小不超过20M。）</Typography.Text>
            </Space>
            <br/>
            <br/>
            <br/>
          </>
        )}
        <Space>
          {attachList.map((item, idx) => {
            return <Button onClick={() => {
              DownloadAttachApi(props.download, history.location.query.name, item)
            }
            } key={item}>下载附件{idx+1}</Button>
          })}
        </Space>
      </>
    );
  }
}
